package com.unism.common.rest.filters;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import com.unism.util.MapTool;

import net.sf.json.JSONNull;

public class ParamFilter implements ContainerRequestFilter {

	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub

		UriInfo uriInfor = requestContext.getUriInfo();
		Iterator iterator = null;
		// post 请求体中的参数
		HashMap<String, Object> param = new HashMap<String, Object>();
		InputStream inputStream = requestContext.getEntityStream();
		String str = inputStreamToString(inputStream);
		Boolean isOk = MapTool.isJSON(str);
		if (null != str && !str.trim().equals("") && isOk) {
			MapTool.parseJSON2Map(str, param);
		}

		// @queryParam
		MultivaluedMap<String, String> queryParam = uriInfor.getQueryParameters();
		iterator = queryParam.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			List<String> value = queryParam.get(key);
			param.put(key, value);
		}
		// @pathParam
		MultivaluedMap<String, String> pathParam = uriInfor.getPathParameters();
		iterator = pathParam.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			List<String> value = pathParam.get(key);
			param.put(key, value);
		}

		checkOutRequestAttribute(param);
		requestContext.setProperty("param", param);
	}

	/**
	 * 校验所有传来的参数，如果参数为空、null则删除该参数
	 * @author wujin wcj@unism.com.cn
	 * @param param
	 * @version 2016年12月9日上午11:47:48
	 */
	private void checkOutRequestAttribute(HashMap<String, Object> hashMap) {
		Iterator<Map.Entry<String, Object>> it = hashMap.entrySet().iterator();  
        while(it.hasNext()){  
            Map.Entry<String, Object> entry=it.next(); 
            Object value = entry.getValue();
            if(null == value || "".equals(value) || value instanceof JSONNull || "\"null\"".equals(value)){  
                it.remove(); 
            }else if (value instanceof LinkedList ) {
				@SuppressWarnings("rawtypes")
				LinkedList linkedList = (LinkedList)value;
				if (linkedList.getFirst().toString().length()==0) {
					it.remove();
				}
			}else if (value instanceof ArrayList ) {
				@SuppressWarnings("rawtypes")
				ArrayList arrayList = (ArrayList)value;
				if (arrayList.size()==0) {
					it.remove();
				}else{
					Iterator iterator  = arrayList.iterator();
					while (iterator.hasNext()) {
						Object object = iterator.next();
						if (object instanceof JSONNull) {
							iterator.remove();
						}
					}
					if (arrayList.size()==0) {
						it.remove();
					}
				}
			}
        }
	}

	private String inputStreamToString(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}
